package service

import (
	"fmt"
	"gorm.io/gorm"
	"gowork/viewExamineNode/dataInit"
	"gowork/viewExamineNode/model"
	"gowork/viewExamineNode/utils"
	"time"
)

type ViewService struct {
	GormDb *gorm.DB
}

func (viewService *ViewService) InsertRegionCheckNode(regionList []*model.Region) (map[string]interface{}, error){

	w := new(utils.Worker)

	viewService.GormDb = dataInit.Db
	gormTx := viewService.GormDb.Begin()

	for _, region := range regionList {
		var indexNodeIdMap = make(map[int]int64)

		for o := 0; o < len(region.CheckNodeList); o++ {
			if o == 0{
				var checkNode = model.CheckNode{
					CheckNodeId:            w.GetId(),
					CheckNodeName:          region.CheckNodeList[o].CheckNodeName,
					NextCheckNodeId:        1,
					ThePreviousCheckNodeId: 1,
					RegionId:               region.RegionId,
					RoleId:                 region.CheckNodeList[o].RoleId,
					CreatedAt:              time.Now(),
					UpdatedAt:              time.Now(),
				}
				err := gormTx.Create(&checkNode).Error
				if err != nil{
					fmt.Println("err：", err)
					gormTx.Rollback()
				}

				indexNodeIdMap[o] = checkNode.CheckNodeId

				for _, user := range region.CheckNodeList[o].UserList {
					var checkNodeUser = model.CheckNodeUser{
						CheckNodeUserId: w.GetId(),
						CheckNodeId:     checkNode.CheckNodeId,
						UserId:          user.UserId,
						UserName:        user.UserName,
						CreatedAt:       time.Now(),
						UpdatedAt:       time.Now(),
					}
					err := gormTx.Create(&checkNodeUser).Error
					if err != nil{
						gormTx.Rollback()
					}
				}

			}else {
				var checkNode = model.CheckNode{
					CheckNodeId:            w.GetId(),
					CheckNodeName:          region.CheckNodeList[o].CheckNodeName,
					NextCheckNodeId:        1,
					ThePreviousCheckNodeId: indexNodeIdMap[o - 1],
					RegionId:               region.RegionId,
					RoleId:                 region.CheckNodeList[o].RoleId,
					CreatedAt:              time.Now(),
					UpdatedAt:              time.Now(),
				}
				err := gormTx.Create(&checkNode).Error
				if err != nil{
					gormTx.Rollback()
				}

				var nextNode model.CheckNode
				err = gormTx.Model(&nextNode).Where("check_node_id = ?", indexNodeIdMap[o - 1]).Update("next_check_node_id", checkNode.CheckNodeId).Error
				if err != nil{
					gormTx.Rollback()
				}

				indexNodeIdMap[o] = checkNode.CheckNodeId

				for _, user := range region.CheckNodeList[o].UserList {
					var checkNodeUser = model.CheckNodeUser{
						CheckNodeUserId: w.GetId(),
						CheckNodeId:     checkNode.CheckNodeId,
						UserId:          user.UserId,
						UserName:        user.UserName,
						CreatedAt:       time.Now(),
						UpdatedAt:       time.Now(),
					}
					err := gormTx.Create(&checkNodeUser).Error
					if err != nil{
						gormTx.Rollback()
					}
				}
			}
		}
	}

	gormTx.Commit()

	return map[string]interface{}{"message":"新增成功", "code":200}, nil
}
